<!-- 该文件和newConfig一样 -->
<template>
	<div class="trigger-configuration-new" v-loading="loading">
		<el-radio-group v-model="state.currentNodeInfoFront.options.fieldOptions.convertType" class="trigger-configuration-new-title mar-b-8" v-if="isShowCode">
            <el-radio-button :label="'mapping'">配置方式</el-radio-button>
            <el-radio-button :label="'code'" v-if="state.trigger_code_gray">代码方式</el-radio-button>
        </el-radio-group>
		<div class="trigger-configuration-new-header" v-if="Object.keys(state.currentNodeInfoFront.options.fieldOptions || {}).length && state.currentNodeInfoFront.options.fieldOptions.convertType === 'mapping'">
			<div class="trigger-configuration-new-header-title">字段映射配置</div>
		</div>
		<div class="trigger-configuration-new-content" v-if="Object.keys(state.currentNodeInfoFront.options.fieldOptions || {}).length && state.currentNodeInfoFront.options.fieldOptions.convertType === 'mapping'">
			<div class="trigger-configuration-new-content-header">
				<div class="trigger-configuration-new-content-header-title" @click="toggleMasterData">
					<i class="iconfont" :class="isShowMasterData ? 'icon-caret-down' : 'icon-caret-right'"></i>
					<div>主数据</div>
				</div>
				<div class="trigger-configuration-new-content-header-select">
					<el-dropdown @command="handleMultipleCommand" trigger="click">
						<span class="el-dropdown-link">
							{{ getMultipleWaysText }} <i class="iconfont icon-caret-down"></i>
						</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item command="1">固定值</el-dropdown-item>
							<el-dropdown-item command="2">对应字段</el-dropdown-item>
							<el-dropdown-item command="3">其他应用表单</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</div>
			</div>
			<newConfigItem
				v-for="(field, index) in toFieldList"
				:key="field.enName"
				:field="field"
				:valueType="state.currentNodeInfoFront.options.fieldOptions.insert[index].valueType"
				:value="state.currentNodeInfoFront.options.fieldOptions.insert[index].value"
				:optionValue="state.currentNodeInfoFront.options.fieldOptions.insert[index]"
				:index="index"
				:fromFieldList="fromFieldList"
				:toFieldList="toFieldList"
				:isShowMasterData="isShowMasterData"
				@change="handleItemChange($event, index)"
      		/>
		</div>
		<div class="trigger-configuration-new-code" v-if="Object.keys(state.currentNodeInfoFront.options.fieldOptions || {}).length && state.currentNodeInfoFront.options.fieldOptions.convertType === 'code'">
			<el-button type="text" @click="openCodeHelp">编码规范及使用帮助</el-button>
			<action-codemirror :value.sync="state.currentNodeInfoFront.options.fieldOptions.convertCode" v-if="state.trigger_code_gray"></action-codemirror>
		</div>
	</div>
</template>

<script>
import { matchFieldToTransform } from '@src/modules/connector/util'
import { getFieldMapping } from '@src/modules/trigger/api/trigger.js';
import state from '@src/modules/trigger/view/setting/util/state.js';
import actionMixin from '../mixins/actionMixin';
import actionCodemirror from '@src/modules/connector/view/setting/components/workflow/components/drawers/actionCodemirror.vue';
import newConfigItem from './newConfigItem.vue';

export default {
	name: "selectConfig",
	mixins: [actionMixin],
	data() {
		return {
			fromFieldList: [],
			toFieldList: [],
			selectFieldList: [],
			isShowMasterData: true,
			selectedCnName: '',
			loading: false,
			isShowCode: false,
		};
	},
	components: {
		actionCodemirror,
		newConfigItem,
	},
	computed: {
		getMultipleWaysText() {
			switch (this.multipleWays) {
				case '1': return '固定值';
				case '2': return '对应字段';
				case '3': return '其他应用表单';
				default: return '多种方式';
			}
		},
		multipleWays() {
			if (state.currentNodeInfoFront.options.fieldOptions.insert.every(item => item.valueType === '1')) {
				return '1';
			} else if (state.currentNodeInfoFront.options.fieldOptions.insert.every(item => item.valueType === '2')) {
				return '2';
			} else if (state.currentNodeInfoFront.options.fieldOptions.insert.every(item => item.valueType === '3')) {
				return '3';
			} else {
				return '0';
			}
		},
		state() {
			return state;
		},
	},
	created() {
		this.loading = true;
		getFieldMapping({
			fromApiIdList: (state.parentNodeApiIdList || []).filter(apiId => apiId !== null && apiId !== 'message' && apiId !== 'code'),
			toApiId: state.currentNodeInfoFront.options.apiId,
		}).then(res => {
			if (res.status === 0) {
				this.fromFieldList = this.changeChildrenKey(this.changeChildrenData(res.data?.fromFieldList));
				this.toFieldList = res.data?.toFieldList;
				this.selectFieldList = res.data?.selectFieldList;
				// 旧版触发器新增时可以配置代码，需要适配，如果没有代码，则不需要显示
				if (Object.keys(state.currentNodeInfoFront.options?.fieldOptions || {}).includes('convertCode')) {
					this.isShowCode = true;
				}
				// 需要用$set绑定响应式数据，否则会失去响应式，导致页面无法操作
				// 如果没有数据
				if (!state.currentNodeInfoFront.options?.fieldOptions?.insert) {
					this.$set(state.currentNodeInfoFront.options, 'fieldOptions', {
						convertType: 'mapping',
						...state.currentNodeInfoFront.options.fieldOptions,
						insert: res.data?.toFieldList.map(field => ({
							toEnName: field.enName,
							operate: null,
							// 默认选中对应字段
							valueType: field.valueTypeList.some(i => i.enName === '2') ? '2' : field.valueTypeList[0]?.enName,
							value: [],
							required: field?.required,
						}))
					});
				} else {
					const insertList = state.currentNodeInfoFront.options?.fieldOptions?.insert || [];

					// 创建一个新的空数组 newFields，结构从 toFieldList 中获取
					const newFields = res.data?.toFieldList.map(field => ({
						toEnName: field.enName,
						operate: null,
						// 默认选中对应字段
						valueType: field.valueTypeList.some(i => i.enName === '2') ? '2' : field.valueTypeList[0]?.enName,
						value: [],
						required: field?.required,
					}));

					// 同步之前的数据到 newFields 中
					newFields.forEach(newField => {
						const existingField = insertList.find(field => field.toEnName === newField.toEnName);
						if (existingField) {
							newField.valueType = existingField.valueType;
							newField.value = existingField.value;
						}
					});

					// 更新 fieldOptions 的 insert 属性
					this.$set(state.currentNodeInfoFront.options, 'fieldOptions', {
						convertType: 'mapping',
						...state.currentNodeInfoFront.options.fieldOptions,
						insert: newFields,
					});
				}
			} else {
				this.$message.error(res?.message);
			}
		}).catch(err => {
			console.log(err)
		}).finally(() => {
			this.loading = false;
		});
	},
	methods: {
		toggleMasterData() {
			this.isShowMasterData = !this.isShowMasterData;
		},
		handleMultipleCommand(value) {
			this.toFieldList.forEach((field, index) => {
				if (field.valueTypeList.some(item => item.enName === value)) {
					if (state.currentNodeInfoFront.options.fieldOptions.insert[index].valueType != value) {
						state.currentNodeInfoFront.options.fieldOptions.insert[index].valueType = value;
						state.currentNodeInfoFront.options.fieldOptions.insert[index].value = [];
					}
				}
			});
		},
		handleItemChange(value, index) {
			console.log(state)
			state.currentNodeInfoFront.options.fieldOptions.insert[index].valueType = value.valueType;
            state.currentNodeInfoFront.options.fieldOptions.insert[index].value = value.value;
			if (value._compatibilityField) {
				// 如果存在兼容性字段，则添加到兼容性列表中
				const existingIndex = state._compatibilityList.findIndex(item => (item.index) == index && item.nodeUniqueId === state.currentNodeInfoFront.uniqueId)
				if (existingIndex === -1) {
					state._compatibilityList.push({
						...value._compatibilityField,
						nodeUniqueId: state.currentNodeInfoFront.uniqueId,
						index: index,
						status: 'select'
					})
				}
				
			}
		},
		// 在列表中查询数据，返回查询到的对象
		findData(list, flg) {
  			for (const item of list) {
    			if (item.enName === flg) {
      				return item;
    			}
    			if (item.children) {
      				const result = this.findData(item.children, flg);
      				if (result.enName === flg) {
        				return result;
      				}
    			}
  			}
  			return {};
		},
		filterAndDisableData(data, enName) {
			// 通过matchFieldToTransform过滤掉数组中不符合条件的元素，如果子元素有相同的则保留父元素，但设置disabled为true，禁用掉父元素，保留子元素
			const targetField = this.findData(this.toFieldList, enName);

			function filterElement(element) {
				const item = {
					...element,
					disabled: !matchFieldToTransform(targetField, element),
				};

				if (element.children) {
					const filteredChildren = element.children.filter(child => filterElement(child));
					if (filteredChildren.length > 0) {
						item.children = filteredChildren;
						return item;
					} else {
						delete item.children;
					}
				}
				return matchFieldToTransform(targetField, item) || item.children ? item : null;
			}
			return data.map(element => filterElement(element)).filter(element => element !== null);
		},
		// 打开编码规范及使用帮助
        openCodeHelp() {
            window.open('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/gre7yumc5sz4ewod/dklg7gkm64cya8l4/ox8c8k8i3hp1g6do.html');
        },
	}
};
</script>

<style lang="scss">
.trigger-configuration-new_cascader-popover{
	.el-cascader-panel{
		min-width: 224px;
		flex-direction: row-reverse;
		.el-cascader-menu{
			width: 224px;
			max-width: 100%;
			&:not(:first-child) {
				border-right: 1px solid #e4e7ed
			}
			.el-cascader-node{
				padding-left: 0px;
			}
		}
		.el-radio{
			left: 0;
			top: 0;
		}
	}
}
</style>

<style scoped lang="scss">
.el-dropdown-link {
	cursor: pointer;
}
.trigger-configuration-new {
	.trigger-configuration-new-header {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.trigger-configuration-new-header-title {
			font-weight: 500;
		}
	}

	.trigger-configuration-new-content {
		background-color: #f5f8fa;
		margin-top: 8px;
		padding: 16px;
		width: 100%;

		&-header {
			display: flex;
			align-items: center;
			height: 24px;
			margin-bottom: 9px;

			&-title {
				width: 182px;
				display: flex;
				align-items: center;
				font-weight: 700;
				user-select: none;
				cursor: pointer;

				i {
					margin-right: 8px;
					font-size: 14px;
				}
			}

			&-select {
				min-width: 100px;
				display: flex;
				justify-content: end;
				align-items: center;

				::v-deep .el-dropdown {
					color: #8c8c8c;
				}
			}
		}
	}
}
.trigger-configuration-new-code {
	align-items: flex-end;
    display: flex;
    flex-direction: column;
	.action-app-codemirror {
		width: 100%;
	}
}
</style>
